package cn.e3mall.sso.service.impl;

import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.utils.E3Result;
import cn.e3mall.common.utils.JsonUtils;
import cn.e3mall.mapper.TbUserMapper;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.pojo.TbUserExample;
import cn.e3mall.pojo.TbUserExample.Criteria;
import cn.e3mall.sso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author ${user}
 * @version 1.0.0
 * @description
 * @date ${date} ${time}
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TbUserMapper userMapper;

    @Autowired
    private JedisClient jedisClient;

    @Value("${USER_SESSION}")
    private String USER_SESSION;

    @Value("${SESSION_EXPIRE}")
    private Integer SESSION_EXPIRE;

    @Override
    public E3Result checkUserData(String data, int type) {
        //设置查询条件
        TbUserExample userExample = new TbUserExample();
        Criteria criteria = userExample.createCriteria();
        //1.判断用户名是否可用
        if (type == 1) {
            criteria.andUsernameEqualTo(data);
            //判断电话是否可用
        } else if (type == 2) {
            criteria.andPhoneEqualTo(data);
            //判断邮箱是否可用
        } else if (type == 3) {
            criteria.andEmailEqualTo(data);
        } else {
            return E3Result.build(400, "所传参数非法！");
        }

        List<TbUser> list = userMapper.selectByExample(userExample);
        if (list != null && list.size() > 0) {
            return E3Result.ok(false);
        }
        return E3Result.ok(true);
    }

    @Override
    public E3Result register(TbUser tbUser) {
        //检查数据有效性
        if (StringUtils.isBlank(tbUser.getUsername())) {
            return E3Result.build(400, "用户名不能为空！");
        }
        
        //校验注册数据
        E3Result result = this.checkUserData(tbUser.getUsername(), 1);
        if (!(Boolean) result.getData()) {
            return E3Result.build(400, "此用户名已经被使用");
        }
        if (StringUtils.isBlank(tbUser.getPassword())) {
            return E3Result.build(400, "密码不能为空");
        }
        if (StringUtils.isNotBlank(tbUser.getPhone())) {
        	//验证注册电话是否可用
            result = this.checkUserData(tbUser.getPhone(), 2);
            if (!(Boolean) result.getData()) {
                return E3Result.build(400, "此手机号已经被使用");
            }
        }
        if (StringUtils.isNotBlank(tbUser.getEmail())) {
        	//校验注册邮箱是否可用
            result = this.checkUserData(tbUser.getEmail(), 3);
            if (!(Boolean) result.getData()) {
                return E3Result.build(400, "此邮件地址已经被使用");
            }
        }

        //补全数据
        tbUser.setCreated(new Date());
        tbUser.setUpdated(new Date());
        //使用MD5加密密码
        String md5pw = DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes());
        tbUser.setPassword(md5pw);
        //添加
        userMapper.insert(tbUser);
        return E3Result.ok();
    }

    @Override
    public E3Result login(String username, String password) {
        //1.判断用户名和密码是否正确
        TbUserExample example = new TbUserExample();
        Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        //查询用户信息
        List<TbUser> users = userMapper.selectByExample(example);
        if (users == null || users.size() == 0) {
            //登录失败
            return E3Result.build(400, "用户名或者密码不正确");
        }
        TbUser user = users.get(0);
        //判断密码
        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
            //登录失败
            return E3Result.build(400, "用户名或者密码不正确");
        }
        //2.生成token令牌
        String token = UUID.randomUUID().toString();
        //3.把用户信息保存到redis中（以token作为key，value就是用户的信息）
        user.setPassword(null);
        jedisClient.set(USER_SESSION + ":" + token, JsonUtils.objectToJson(user));
        //4.设置过期时间
        jedisClient.expire(USER_SESSION + ":" + token, SESSION_EXPIRE);
        //5.返回token
        return E3Result.ok(token);
    }

    @Override
    public E3Result getUserByToken(String token) {
    	//根据token查询redis
        String json = jedisClient.get(USER_SESSION + ":" + token);
        if(StringUtils.isBlank(json)){
        	//如果没有数据，就返回用户已经过期
            return  E3Result.build(400, "token已经过期！");
        }

        TbUser user = JsonUtils.jsonToPojo(json, TbUser.class);
        //重新设置过期时间
        jedisClient.expire(USER_SESSION + ":" + token, SESSION_EXPIRE);
        //返回结果
        return E3Result.ok(user);
    }

    @Override
    public E3Result logout(String token) {
        jedisClient.expire(USER_SESSION + ":" +token, 0);
        return E3Result.ok();
    }
}
